<?php
class cartModel {
	function __construct() {
		if (isset($_SESSION["products"])) {
			$this -> products = $_SESSION["products"];
		} else {
			$this -> products = array();
			$_SESSION["products"] = $this -> products;
		}

		$this -> message = "";
	}

	function add($id, $quantity) {
		if (array_key_exists($id, $this -> products)) {
			$this -> products[$id]["quantity"] += $quantity;
		} else {
			$this -> products[$id] = array("id" => $id, "quantity" => $quantity);
		}
		$_SESSION["products"] = $this -> products;

		$this -> message = "Add success";
	}

	function remove($id) {
		unset($this -> products[$id]);
		$_SESSION["products"] = $this -> products;
		$this -> message = "Remove success";
	}

	function update($id, $quantity) {
		$this -> products[$id]["quantity"] = $quantity;

		$_SESSION["products"] = $this -> products;
	}

	function getViewedProduct($product_id = 0) {
		$flag = FALSE;
		if ($this -> phpsession -> get('viewed_product') == '')
			$this -> phpsession -> save('viewed_product', $product_id);
		else {
			$str = $product_id;
			$viewed_array = explode(':', $this -> phpsession -> get('viewed_product'));
			foreach ($viewed_array as $a) {
				if ($str == $a) {$flag = FALSE;
					break;
				} else {$flag = TRUE;
				}
			}
		}
		if ($flag)
			$this -> phpsession -> save('viewed_product', $this -> phpsession -> get('viewed_product') . ':' . $str);

		$product_ids = explode(':', $this -> phpsession -> get('viewed_product'));
		if (count($product_ids) > 4) {
			array_shift($product_ids);
			$b = '';
			foreach ($product_ids as $id) {
				if ($b == '')
					$b .= $id;
				else
					$b .= ':' . $id;
			}
			$this -> phpsession -> save('viewed_product', $b);
		}
		return explode(':', $this -> phpsession -> get('viewed_product'));
	}

}
?>